package com.liugang.oss_demo.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Component
public class OSSUtil {

    // OSS endpoint，根据你的实际情况填写
    private static String endpoint = "";
    // OSS access key id，根据你的实际情况填写
    private static String accessKeyId = "";
    // OSS access key secret，根据你的实际情况填写
    private static String accessKeySecret = "";
    // OSS bucket名称，根据你的实际情况填写
    private static String bucketName = "";

    private static String PNG = "png";
    private static String JPEG = "jpeg";
    private static String DOCX = "docx";

    /**
     *
     * @param objectName "file.txt"; // 在 OSS 上的文件名，可以自定义
     */
    public static void upload(MultipartFile content, String objectName) {

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {

            // 上传文件
            PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));

            // 打印ETag（上传成功时会返回）
            System.out.println("ETag: " + putObjectResult.getETag());
            System.out.println("文件上传成功");

            // 返回图片地址
            String url = "https://" + bucketName + "." + endpoint + "/" + objectName;
            System.out.println("文件地址：" + url);
            // 这个地址url 可以直接访问 如果不是图片，则需要设置contentType 如果是图片，则不需要设置contentType
            // 如果是图片，返回前端，前端可以根据这个地址访问图片

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }

    /**
     *
     * @param objectName "file.txt"; // 要下载的文件在 OSS 上的文件名
     * @param localFilePath "/path/to/save/file.txt"; // 下载后保存到本地的文件路径
     */
    public static void download(String objectName, String localFilePath) {

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建GetObjectRequest对象
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);

            // 执行下载请求，获取OSSObject对象
            OSSObject ossObject = ossClient.getObject(getObjectRequest);

            // 获取文件流
            InputStream inputStream = ossObject.getObjectContent();

            // 将文件流保存到本地文件
            saveInputStreamToFile(inputStream, localFilePath);


            System.out.println("文件下载成功");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }

    // 将输入流保存到文件
    private static void saveInputStreamToFile(InputStream inputStream, String filePath) throws IOException {
        byte[] buffer = new byte[1024];
        int bytesRead;
        FileOutputStream outputStream = new FileOutputStream(new File(filePath));
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
    }

    /**
     *
     * @param objectName "file.txt"; // 要下载的文件在 OSS 上的文件名
     */
    public static void download(String objectName, String fileName, HttpServletResponse response) {

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建GetObjectRequest对象
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);

            // 执行下载请求，获取OSSObject对象
            OSSObject ossObject = ossClient.getObject(getObjectRequest);

            // 获取文件流
            InputStream inputStream = ossObject.getObjectContent();

            ServletOutputStream outputStream = response.getOutputStream();

            String fileExtension = "";
            int dotIndex = objectName.lastIndexOf(".");
            if (dotIndex > 0) {
                fileExtension = objectName.substring(dotIndex + 1); // 包括点号
            }
            if (PNG.equals(fileExtension) || JPEG.equals(fileExtension)) {
                response.setContentType("image/jpeg");
            } else if (DOCX.equals(fileExtension)) {
                response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            }

            // 设置Content-Disposition头部，指定attachment; filename="example.docx"
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            outputStream.close();
            inputStream.close();
            System.out.println("文件下载成功");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }

    /**
     *
     * @param objectName // 要删除的文件在 OSS 上的文件名
     */
    public static void deleteFile(String objectName) {

        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 执行删除文件请求
            ossClient.deleteObject(bucketName, objectName);

            System.out.println("文件删除成功");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
    }

}
